<template>
  <div class="container">
    <el-row :gutter="8">
      <el-col v-for="(item, index) of countData" :key="index" :span="12">
        <div class="data-card-contaienr" >
          <DataCard
            :title="item.title"
            :num="item.num"
            :color="item.color"
          />
        </div>
      </el-col>
    </el-row>

    <el-card shadow="never" body-style="height:300px;padding: 0">
      <template #header>
        <span>历史任务动态</span>
        <el-select
          style="width: 100px;float: right; margin-top: -5px"
          size="mini"
          v-model="historyTaskMonth"
          placeholder="请选择本年月份"
        >
          <el-option
            v-for="item in month"
            :key="item"
            :label="item + '月'"
            :value="item"
          ></el-option>
        </el-select>
      </template>
      <v-chart :options="historyTaskOptions"></v-chart>
    </el-card>

    <el-card shadow="never" style="margin-top: 8px;" body-style="height:600px;padding: 0">
      <template #header>
        <span>绩效</span>
      </template>
      <v-chart :options="achievementsOptions"></v-chart>
    </el-card>

    <OperationMaintainContent></OperationMaintainContent>
  </div>
</template>

<script>
import ECharts from 'vue-echarts'
import DataCard from './components/DataCard.vue'
import OperationMaintainContent from './components/OperationMaintainContent'

import { useStatistic, task } from '@/api/activiti.js'

import { getHistoryTaskConfig, getAchievementsConfig } from './dataConfig'

export default {
  components: {
    DataCard,
    'v-chart': ECharts,
    OperationMaintainContent
  },
  data () {
    const date = new Date()
    this.year = date.getFullYear()
    this.month = date.getMonth() + 1
    this.day = date.getDate()

    return {
      countData: [
        { key: 'repair', title: '正在维修任务', num: 0, color: '#ff7e67' },
        { key: 'inspection', title: '正在巡检任务', num: 0, color: '#006a71' },
        { key: 'maintain', title: '正在维保任务', num: 0, color: '#68b0ab' },
        { key: 'patrol', title: '正在巡更任务', num: 0, color: '#9a8194' }
      ],

      historyTaskOptions: {},
      historyTaskMonth: this.month,
      achievementsOptions: {}
    }
  },
  watch: {
    historyTaskMonth () {
      this.renderHistoryTask()
    }
  },
  computed: {
    countDataMap () {
      return this.countData.reduce((acc, item) => {
        acc[item.key] = item
        return acc
      }, {})
    }
  },
  mounted () {
    this.getTaskNum()
    this.renderHistoryTask()
    this.renderAchievements()
  },
  methods: {
    async getTaskNum () {
      try {
        // 获取任务数量
        const res = await task.getNum([
          'repair',
          'maintain',
          'patrol',
          'inspection'
        ])

        res.forEach((item) => {
          const countDataItem = this.countDataMap[item.KEY_]
          countDataItem.num = item.sum
        })
      } catch (error) {
        console.log('获取任务数量', error)
      }
    },
    async renderHistoryTask () {
      const defaultDataMap = {
        repair: { name: '维修任务', type: 'line', data: [] },
        inspection: { name: '巡检任务', type: 'line', data: [] },
        maintain: { name: '维保任务', type: 'line', data: [] },
        patrol: { name: '巡更任务', type: 'line', data: [] }
      }
      const legendData = []
      const xAxisData = []

      try {
        const parmas = {
          data: getHistoryTaskConfig(this.historyTaskMonth)
        }

        const { data } = await useStatistic(7812441631, parmas)

        let lastDay = this.day

        if (this.historyTaskMonth !== this.month) {
          const date = new Date(this.year, this.historyTaskMonth - 1, 0)
          lastDay = date.getDate()
        }

        let firstCycle = true

        Object.keys(data).forEach(key => {
          let item = data[key]

          // 重置日期
          if (!Array.isArray(item)) {
            item = Object.keys(item).reduce((acc, key) => {
              const tempKey = key.split('/')[2]
              acc[tempKey] = item[key]
              return acc
            }, {})
          } else {
            item = {}
          }

          const name = defaultDataMap[key].name
          // 添加 legend
          legendData.push(name)

          // 循环收集日期数据
          for (let i = 0; i < lastDay; i++) {
            if (firstCycle) {
            // 第一次循环收集 x 轴的值
              xAxisData.push(`${i + 1}日`)
            }

            const _item = item[i] || 0

            defaultDataMap[key].data.push(_item)
          }

          firstCycle = false
        })
      } catch (error) {
        console.log('渲染历史任务动态数据失败', error)
      }

      this.historyTaskOptions = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          type: 'scroll',
          left: 16,
          right: 16,
          top: 16,
          data: legendData
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: Object.values(defaultDataMap)
      }
    },
    async renderAchievements () {
      try {
        const parmas = {
          data: getAchievementsConfig(this.historyTaskMonth)
        }

        const { data } = await useStatistic(81283116, parmas)

        console.log(data)

        const defaultDataMap = {
          repair: { name: '维修任务', type: 'bar', stack: '总量', data: [] },
          inspection: { name: '巡检任务', type: 'bar', stack: '总量', data: [] },
          maintain: { name: '维保任务', type: 'bar', stack: '总量', data: [] },
          patrol: { name: '巡更任务', type: 'bar', stack: '总量', data: [] }
        }
        const legendData = ['维修任务', '巡检任务', '维保任务', '巡更任务']
        const xAxisData = []

        const userDataMap = {}

        Object.keys(data).forEach(key => {
          const users = data[key]

          users.forEach(user => {
            if (!userDataMap[user.userName]) {
              userDataMap[user.userName] = {}
            }

            userDataMap[user.userName][key] = user.num
          })
        })

        Object.keys(userDataMap).forEach(userName => {
          const userTaskNumMap = userDataMap[userName]
          xAxisData.push(userName)

          Object.keys(userTaskNumMap).forEach(taskType => {
            const taskNum = userTaskNumMap[taskType]
            defaultDataMap[taskType].data.push(taskNum)
          })
        })

        this.achievementsOptions = {
          tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          legend: {
            type: 'scroll',
            top: 16,
            left: 16,
            right: 16,
            data: legendData
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value'
          },
          yAxis: {
            type: 'category',
            data: xAxisData
          },
          dataZoom: [
            {
              type: 'slider',
              yAxisIndex: 0,
              filterMode: 'empty',
              start: 100,
              end: 92,
              left: 0
            }
          ],
          series: Object.values(defaultDataMap)
        }
      } catch (error) {
        console.log('渲染绩效数据失败', error)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 8px;
  background-color: #fff;
}

.data-card-contaienr {
  margin-bottom: 8px;
}

::v-deep .el-card__header {
  font-size: 14px;
}
</style>
